package com.wanli.storemobile.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import com.wanli.storemobile.R;
import com.wanli.storemobile.base.DataCallBack;
import com.wanli.storemobile.bean.BankDeposiAddressListBean;
import com.wanli.storemobile.bean.BankListBean;
import com.wanli.storemobile.bean.SubBranchListBean;
import com.wanli.storemobile.homepage.adapter.AddressAdapter;
import com.wanli.storemobile.homepage.model.HomePageModelImpl;
import com.wanli.storemobile.homepage.model.IHomePageModel;
import com.wanli.storemobile.widget.ViewLoading;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Author:HWC
 */
public class BankDepositDialog extends DialogFragment {


    @BindView(R.id.tv_provience_name)
    TextView tvProvienceName;
    @BindView(R.id.view_provience)
    View viewProvience;
    @BindView(R.id.ll_provience)
    LinearLayout llProvience;

    @BindView(R.id.tv_city_name)
    TextView tvCityName;
    @BindView(R.id.view_city)
    View viewCity;
    @BindView(R.id.ll_city)
    LinearLayout llCity;

    @BindView(R.id.tv_area_name)
    TextView tvAreaName;
    @BindView(R.id.view_area)
    View viewArea;
    @BindView(R.id.ll_area)
    LinearLayout llArea;

    @BindView(R.id.tv_bank_name)
    TextView tvBankName;
    @BindView(R.id.view_bank)
    View viewBank;
    @BindView(R.id.ll_bank)
    LinearLayout llBank;
    @BindView(R.id.tv_branch_bank_name)
    TextView tvBranchBankName;
    @BindView(R.id.view_branch_bank)
    View viewBranchBank;
    @BindView(R.id.ll_branch_bank)
    LinearLayout llBranchBank;

    @BindView(R.id.rv_address)
    RecyclerView rv_address;

    @BindView(R.id.radio_group)
    RadioGroup radio_group;


    @BindView(R.id.btn_city)
    RadioButton btn_city;

    @BindView(R.id.btn_area)
    RadioButton btn_area;
    @BindView(R.id.edit_bank_search)
    EditText editBankSearch;
    @BindView(R.id.view_bank_cancel)
    View viewBankCancel;
    @BindView(R.id.ll_root_bank)
    LinearLayout llRootBank;
    @BindView(R.id.ll_root_branchbank)
    LinearLayout llRootBranchbank;
    @BindView(R.id.edit_branch_bank_search)
    EditText editBranchBankSearch;
    @BindView(R.id.view_branch_bank_cancel)
    View viewBranchBankCancel;
    @BindView(R.id.tv_branch_bank_search)
    TextView tvBranchBankSearch;
    private Dialog dialog;
    private OnCallBackListener onCallBackListener;
    private Activity mActivity;

    private IHomePageModel homePageModel = new HomePageModelImpl();
    private AddressAdapter provienceAdapter;
    private List<BankDeposiAddressListBean.DataBean> addressList = new ArrayList<>();
    private String open_acc_bank_name;
    private String open_acc_bank_type;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        initWindow();
        View view = inflater.inflate(R.layout.dialog_bank_deposit, null);
        ButterKnife.bind(this, view);
        mActivity = getActivity();
        initView();
        initData();
        setListener();
        return view;
    }


    int code = 0000;
    int level = 1;

    String provinceName = "";
    String provinceCode = "";
    String cityName = "";
    String cityCode = "";
    String areaName = "";
    String areaCode = "";

    private String bank_name = "";
    private String bank_type = "";
    private String isAddress = "1";

    private void initData() {
        requestGetRegion(code, level);
    }

    private void setListener() {
        provienceAdapter = new AddressAdapter(addressList, 1);

        rv_address.setLayoutManager(new LinearLayoutManager(mActivity));
        rv_address.setAdapter(provienceAdapter);


        provienceAdapter.setOnCallBackListener(new AddressAdapter.OnCallBackListener() {
            @Override
            public void onCallBack(String name, String code) {


                if (level == 1) {
                    provinceName = name;
                    provinceCode = code;
                    tvProvienceName.setText(provinceName);

                    cityName = "";
                    cityCode = "";
                    tvCityName.setText("市");

                    areaName = "";
                    areaCode = "";
                    tvAreaName.setText("区/县");

                } else if (level == 2) {

                    cityName = name;
                    cityCode = code;

                    tvCityName.setText(cityName);

                    areaName = "";
                    areaCode = "";
                    tvAreaName.setText("区/县");

                } else if (level == 3) {
                    areaName = name;
                    areaCode = code;
                    tvAreaName.setText(areaName);
                } else if (level == 4) {

                    bank_name = name;
                    bank_type = code;
                    tvBankName.setText(bank_name);
                } else if (level == 5) {

                    open_acc_bank_name = name;
                    open_acc_bank_type = code;
                    tvBranchBankName.setText(open_acc_bank_name);
                }

                level++;

                if (level == 4) {
                    requestGetBank("");
                } else if (level == 5) {
                    requestGetOpenBank("", bank_type, cityCode);
                } else if (level == 6) {

                    onCallBackListener.onCallBack(provinceName, cityName, areaName, bank_name, bank_type, open_acc_bank_name, open_acc_bank_type);


                    dismiss();
                } else {
                    requestGetRegion(Integer.valueOf(code), level);
                }

                setDisplay(level);


                Log.e("address--name", name);
                Log.e("address--code", code);
                Log.e("address--level", String.valueOf(level));


            }
        });

        radio_group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.btn_city:
                        level = 5;
                        isAddress = "1";
                        requestGetOpenBank("", bank_type, cityCode);
                        break;
                    case R.id.btn_area:
                        level = 5;
                        isAddress = "2";
                        requestGetOpenBank("", bank_type, areaCode);
                        break;
                }
            }
        });


        editBankSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    viewBankCancel.setVisibility(View.VISIBLE);
                } else {
                    viewBankCancel.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        editBankSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String bankName = editBankSearch.getText().toString();
                    requestGetBank(bankName);
                    return true;
                }
                return false;
            }
        });


        editBranchBankSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    viewBranchBankCancel.setVisibility(View.VISIBLE);
                } else {
                    viewBranchBankCancel.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        editBranchBankSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String branchName = editBranchBankSearch.getText().toString();
                    if ("1".equals(isAddress)) {
                        requestGetOpenBank(branchName, bank_type, cityCode);
                    } else {
                        requestGetOpenBank(branchName, bank_type, areaCode);
                    }

                    return true;
                }
                return false;
            }
        });
    }


    public static BankDepositDialog newInstance(String type) {
        Bundle args = new Bundle();
        BankDepositDialog fragment = new BankDepositDialog();
        args.putString("type", type);
        fragment.setArguments(args);
        return fragment;
    }

    public void setOnCallBackListener(OnCallBackListener onCallBackListener) {
        this.onCallBackListener = onCallBackListener;
    }

    private void initView() {
        btn_city.setChecked(true);
        btn_area.setChecked(false);
    }


    private void requestGetBank(String bank_name) {

        homePageModel.requestGetBank(bank_name, new DataCallBack<BankListBean>() {
            @Override
            public void onSuccessful(BankListBean bean) {

                List<BankListBean.DataBean> data = bean.getData();
                addressList.clear();

                for (int i = 0; i < data.size(); i++) {
                    BankDeposiAddressListBean.DataBean dataBean = new BankDeposiAddressListBean.DataBean();

                    dataBean.setArea_name(data.get(i).getBank_name());
                    dataBean.setCode(data.get(i).getBank_type());

                    if ("".equals(bank_name)) {
                        addressList.add(dataBean);
                    } else {
                        if (data.get(i).getBank_name().contains(bank_name)) {
                            addressList.add(dataBean);
                        }

                    }

                }


                provienceAdapter.notifyDataSetChanged();


                String s = new Gson().toJson(bean);

                Log.e("address--银行卡", s);

            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });


    }

    private void requestGetOpenBank(String bank_name, String bank_type, String city_code) {

        if (TextUtils.isEmpty(city_code)){
            city_code = provinceCode;
        }


        homePageModel.requesGetOpenBank(bank_type, city_code, new DataCallBack<SubBranchListBean>() {
            @Override
            public void onSuccessful(SubBranchListBean bean) {

                List<SubBranchListBean.DataBean> data = bean.getData();

                addressList.clear();

                for (int i = 0; i < data.size(); i++) {
                    BankDeposiAddressListBean.DataBean dataBean = new BankDeposiAddressListBean.DataBean();

                    dataBean.setArea_name(data.get(i).getOpen_acc_bank_name());
                    dataBean.setCode(data.get(i).getOpen_acc_bank_type());


                    if ("".equals(bank_name)) {
                        addressList.add(dataBean);
                    } else {
                        if (data.get(i).getOpen_acc_bank_name().contains(bank_name)) {
                            addressList.add(dataBean);
                        }

                    }


                }

                provienceAdapter.notifyDataSetChanged();


                String s = new Gson().toJson(bean);

                Log.e("address--支行银行卡", s);
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public void setDisplay(int type) {


        if (type == 5) {
            radio_group.setVisibility(View.VISIBLE);
            llRootBranchbank.setVisibility(View.VISIBLE);
        } else {
            radio_group.setVisibility(View.GONE);
            llRootBranchbank.setVisibility(View.GONE);
        }

        if (type == 4) {
            llRootBank.setVisibility(View.VISIBLE);
        } else {
            llRootBank.setVisibility(View.GONE);
        }


        viewProvience.setVisibility(View.INVISIBLE);
        viewCity.setVisibility(View.INVISIBLE);
        viewArea.setVisibility(View.INVISIBLE);
        viewBank.setVisibility(View.INVISIBLE);
        viewBranchBank.setVisibility(View.INVISIBLE);

        if (type == 1) {
            viewProvience.setVisibility(View.VISIBLE);
        }
        if (type == 2) {
            viewCity.setVisibility(View.VISIBLE);
        }
        if (type == 3) {
            viewArea.setVisibility(View.VISIBLE);
        }
        if (type == 4) {
            viewBank.setVisibility(View.VISIBLE);
        }
        if (type == 5) {
            viewBranchBank.setVisibility(View.VISIBLE);
        }

    }

    public void requestGetRegion(int code, int levelNnu) {
        ViewLoading.showProgress(mActivity, "加载中......");
        homePageModel.requestGetRegion(code, level, new DataCallBack<BankDeposiAddressListBean>() {
            @Override
            public void onSuccessful(BankDeposiAddressListBean bean) {
                addressList.clear();
                addressList.addAll(bean.getData());
                provienceAdapter.notifyDataSetChanged();

                if (3 == levelNnu && addressList.size() == 0) {
                    setDisplay(4);
                    level++;
                    requestGetBank("");
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }


    //设置window属性
    private void initWindow() {
        //去掉dialog的标题
        dialog = this.getDialog();
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(true);
        Window window = dialog.getWindow();
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        window.getAttributes().windowAnimations = R.style.commomDialog;
        window.setAttributes(lp);
        window.setBackgroundDrawable(new ColorDrawable());
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @OnClick({R.id.ll_provience, R.id.ll_city, R.id.ll_area, R.id.ll_bank, R.id.ll_branch_bank, R.id.tv_bank_search, R.id.view_bank_cancel, R.id.tv_branch_bank_search, R.id.view_branch_bank_cancel})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_provience:
                setDisplay(1);
                level = 1;
                requestGetRegion(0000, level);
                break;
            case R.id.ll_city:

                if ("".equals(provinceName)) {
                    Toast.makeText(mActivity, "请选择省", Toast.LENGTH_SHORT).show();
                    return;
                }
                setDisplay(2);
                level = 2;
                requestGetRegion(Integer.valueOf(provinceCode), level);
                break;
            case R.id.ll_area:
                if ("".equals(cityName)) {
                    Toast.makeText(mActivity, "请选择市", Toast.LENGTH_SHORT).show();
                    return;
                }
                setDisplay(3);
                level = 3;
                requestGetRegion(Integer.valueOf(cityCode), level);
                break;
            case R.id.ll_bank:
                level = 4;
                requestGetBank("");
                setDisplay(4);

                break;
            case R.id.ll_branch_bank:
                if ("".equals(bank_name)) {
                    Toast.makeText(mActivity, "请选择总行", Toast.LENGTH_SHORT).show();
                    return;
                }
                level = 5;
                requestGetOpenBank("", bank_type, cityCode);
                setDisplay(5);

                break;
            case R.id.tv_bank_search:
                String bankName = editBankSearch.getText().toString();
                requestGetBank(bankName);
                break;
            case R.id.view_bank_cancel:
                editBankSearch.setText("");
                break;
            case R.id.tv_branch_bank_search:
                String branchName = editBranchBankSearch.getText().toString();

                if ("1".equals(isAddress)) {
                    requestGetOpenBank(branchName, bank_type, cityCode);
                } else {
                    requestGetOpenBank(branchName, bank_type, areaCode);
                }


                break;
            case R.id.view_branch_bank_cancel:
                editBranchBankSearch.setText("");
                break;
        }
    }

    public interface OnCallBackListener {
        void onCallBack(String provinceName, String cityName, String areaName, String bank_name, String bank_type, String open_acc_bank_name, String open_acc_bank_type);
    }
}
